var app = getApp()
var appid = 'wx88b04e459d594722'
var appSecret = '8546c3828903b53f9d1fd3527d063dbd'
var app = getApp()
var domain = app.data.host
var openidUrl = domain + 'getOpenid';
var httpUtil=require("../utils/httpUtil.js")
// 获取用户的openID
function getOpenId(cb) {
  getSession(data=>{
    console.log(data)
    cb(data.openid)
  })
}
//获取token码
function getAccessToken(cb) {
  wx.request({
    url: domain + '/user/getToken',
    method: 'GET',
    success: function(res) {
      var token = res.data
      console.log(token)
      cb(token)
    }
  })
}
//获取用户session_key和openid
function getSession(cb) {
  getLoginCode(code=> {
    httpUtil.get(openidUrl, { js_code: code},res=>{
      console.log(res)
      var openid = res.data.openid
      var session_key = res.data.session_key
      var userSession = {
        openid: openid,
        sessionKey: session_key
      }
      app.data.userSession = userSession
      cb(userSession)
    })
  })
}

// 获取登陆码
function getLoginCode(cb) {
  wx.login({
    success: function(res) {
      var code = res.code
      cb(code)
    },
    fail: function(e) {
      console.log('用户登录失败')
    }
  })
}
//获取sessionKey
function getSessionKey(cb) {
  // getSession(function (data) {
  //   cb(data.sessionKey)
  // })
  wx.checkSession({
    success: function(res) {
      if (res.errMsg == "checkSession:ok") {
        var sessionKey = app.data.userSession.sessionKey
        cb(sessionKey)
      } else {
        getSession(function(data) {
          cb(data.sessionKey)
        })
      }
    },
    fail: function() {
      getSession(function(data) {
        cb(data.sessionKey)
      })
    }
  })
}
module.exports = {
  getAccessToken: getAccessToken,
  getLoginCode: getLoginCode,
  getSession: getSession,
  getSessionKey: getSessionKey,
  getOpenId: getOpenId,
}